package com.wwj.depository.controller;

import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.wwj.common.constant.CommonCodeEnum;
import com.wwj.common.entitiy.R;
import com.wwj.depository.constant.ConstantFinal;
import com.wwj.depository.entity.DepositoryExpressInformationEntity;
import com.wwj.depository.entity.DepositoryLocationEntity;
import com.wwj.depository.service.DepositoryLocationService;
import com.wwj.depository.service.ExpressService;
import com.wwj.depository.utils.StorageCalculateUtil;
import com.wwj.depository.vo.AddLocationVo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/depository")
public class DepositoryLocationController {

    @Resource
    private DepositoryLocationService depositoryLocationService;

    @Resource
    private ExpressService expressService;

    /**
     * 获取所有剩余仓库的列表
     * http://127.0.0.1:88/api/depository/getOption
     */
    @GetMapping("/getOption")
    private R<Object> getOption(){
        // 构建条件
        QueryWrapper<DepositoryLocationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ConstantFinal.FIELD_LOCATION_STORAGE, ConstantFinal.VALUE_LOCATION_NO_STORAGE);
        List<DepositoryLocationEntity> list = depositoryLocationService.list(queryWrapper);
        return R.ok(CommonCodeEnum.SUCCESS.getCode(),CommonCodeEnum.SUCCESS.getMsg(),list);
    }

    /**
     * 获取仓库的所有列表信息
     *  http://127.0.0.1:88/api/depository/getDepositoryData/1/8?query=xxx
     */
    @GetMapping("/getDepositoryData/{currentPage}/{pageSize}")
    private R<Object> getDepositoryData(@PathVariable("currentPage") String currentPage,
                                        @PathVariable("pageSize") String pageSize,
                                        @RequestParam(value = "query",required = false) String query){
        PageInfo<DepositoryLocationEntity> pageInfo = depositoryLocationService.selectDepositoryData(currentPage, pageSize, query);
        return R.ok(CommonCodeEnum.SUCCESS.getCode(), CommonCodeEnum.SUCCESS.getMsg(), pageInfo);
    }

    /**
     * 删除单个仓库信息
     *  http://127.0.0.1:88/api/depository/removeOne?locationId=1
     */
    @DeleteMapping("/removeOne")
    private R<Object> removeOne(@RequestParam("locationId") String locationId) {
        // 删除判断是否该仓位有快递
        // 查询快递表是否有仓位信息
        QueryWrapper<DepositoryExpressInformationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ConstantFinal.FIELD_LOCATION_ID, locationId);
        DepositoryExpressInformationEntity expressResult = expressService.getOne(queryWrapper);
        if (expressResult != null) {
            // 仓位还有快递不允许删除
            return R.error(CommonCodeEnum.EXPRESS_EXIST.getCode(), CommonCodeEnum.EXPRESS_EXIST.getMsg());
        }
        depositoryLocationService.removeById(locationId);
        return R.ok("删除单个仓位信息成功");
    }

    /**
     * 更新仓库的占用/不占用状态
     * http://127.0.0.1:88/api/depository/updateLocationStorage?locationId=1
     */
    @PutMapping("/updateLocationStorage")
    private R<Object> updateLocationStorage(@RequestParam("locationId") String locationId){
        // 查询仓库id是否有占用的快递
        QueryWrapper<DepositoryExpressInformationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ConstantFinal.FIELD_LOCATION_ID, locationId).isNull(ConstantFinal.FIELD_INFORMATION_SIGN_TIME);
        DepositoryExpressInformationEntity expressResult = expressService.getOne(queryWrapper);
        // 查询仓位id详细信息
        DepositoryLocationEntity depositoryLocationEntity = depositoryLocationService.getById(locationId);
        if (ConstantFinal.VALUE_LOCATION_IS_STORAGE.equals(depositoryLocationEntity.getLocationStorage())) {
            // 请求占用状态修改不占用状态
            if (expressResult != null) {
                // 并且快递占用了这个仓位
                return R.error(CommonCodeEnum.EXPRESS_EXIST.getCode(), CommonCodeEnum.EXPRESS_EXIST.getMsg());
            }
            // 允许修改
            depositoryLocationEntity.setLocationStorage(ConstantFinal.VALUE_LOCATION_NO_STORAGE); // 设置为不占用状态
            depositoryLocationService.updateById(depositoryLocationEntity);
            return R.ok("修改成功");
        }else if (ConstantFinal.VALUE_LOCATION_NO_STORAGE.equals(depositoryLocationEntity.getLocationStorage())){
            // 请求不占用状态修改占用状态
            depositoryLocationEntity.setLocationStorage(ConstantFinal.VALUE_LOCATION_IS_STORAGE);
            depositoryLocationService.updateById(depositoryLocationEntity);
            return R.ok("修改成功");
        }
        return R.error(CommonCodeEnum.ERROR.getCode(), CommonCodeEnum.ERROR.getMsg());
    }

    /**
     * 批量删除快递 删除方式2
     * http://127.0.0.1:88/api/depository/batchDelete2
     */
    @DeleteMapping("/batchDelete2")
    private R<Object> batchDelete2(@RequestBody List<DepositoryLocationEntity> depositoryLocationEntityList){
        for (DepositoryLocationEntity item : depositoryLocationEntityList) {
            DepositoryLocationEntity locationEntity = depositoryLocationService.getById(item.getLocationId());
            if (ConstantFinal.VALUE_LOCATION_IS_STORAGE.equals(locationEntity.getLocationStorage())) {
                // 存在占用状态
                return R.error(CommonCodeEnum.EXPRESS_EXIST.getCode(),CommonCodeEnum.EXPRESS_EXIST.getMsg());
            }
        }
        // 没有占用状态就批量删除
        List<String> ids= new ArrayList<>();
        depositoryLocationEntityList.forEach(item -> {
            ids.add(item.getLocationId());
        });
        depositoryLocationService.removeByIds(ids);
        return R.ok("批量删除成功");
    }

    /**
     * 批量删除快递：仓位数末尾删除
     *  http://127.0.0.1:88/api/depository/batchDelete1?deleteNumber=1
     */
    @DeleteMapping("/batchDelete1")
    private R<Object> batchDelete1(@RequestParam("deleteNumber") String deleteNumber){
        // 全表降序排列
        QueryWrapper<DepositoryLocationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc(ConstantFinal.FIELD_LOCATION_ID);
        List<DepositoryLocationEntity> descList = depositoryLocationService.list(queryWrapper);
        // 存放批量删除的ids
        List<String> ids = new ArrayList<>();
        // 判断占用情况
        for (int i = 0; i < Integer.parseInt(deleteNumber); i++) {
            DepositoryLocationEntity locationEntity = descList.get(i);
            if (ConstantFinal.VALUE_LOCATION_IS_STORAGE.equals(locationEntity.getLocationStorage())) {
                // 存在占用情况
                return R.error(CommonCodeEnum.EXPRESS_EXIST.getCode(), CommonCodeEnum.EXPRESS_EXIST.getMsg());
            }
            ids.add(locationEntity.getLocationId());
        }
        // 执行批量删除
        depositoryLocationService.removeByIds(ids);
        return R.ok("批量删除成功");
    }

    /**
     * 通过数量方式新增
     * http://127.0.0.1:88/api/depository/addNumber
     */
    @PostMapping("/addNumber")
    private R<Object> addNumber(@RequestParam("addNumber") String addNumber){
        // 查出最后一个仓库号
        QueryWrapper<DepositoryLocationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc(ConstantFinal.FIELD_LOCATION_ID).last("limit 1"); // 降序排列
        List<DepositoryLocationEntity> locationEntities = depositoryLocationService.list(queryWrapper);
        // 调用工具类获取自动生成的仓库名
        List<String> list = StorageCalculateUtil.storageCalculation(locationEntities.get(0).getLocationName(), 20, Integer.parseInt(addNumber), 20);
        // 创建仓位List
        // todo 可以选择抽取方法
        List<DepositoryLocationEntity> locationEntityList = new ArrayList<>();
        list.forEach(item -> {
            DepositoryLocationEntity depositoryLocationEntity = new DepositoryLocationEntity();
            depositoryLocationEntity.setLocationName(item);
            depositoryLocationEntity.setLocationStorage(ConstantFinal.VALUE_LOCATION_NO_STORAGE);
            locationEntityList.add(depositoryLocationEntity);
        });
        // 批量保存
        depositoryLocationService.saveBatch(locationEntityList);
        return R.ok("批量增加成功");
    }

    /**
     * 通过开始-结尾方式添加仓库
     * http://127.0.0.1:88/api/depository/addStartEnd
     */
    @PostMapping("/addStartEnd")
    private R<Object> addStartEnd(@RequestBody AddLocationVo addLocationVo){
        // 查询仓库范围内是否存在同名仓库
        List<String> listRange = StorageCalculateUtil.storageRange(addLocationVo.getStartLocation(), addLocationVo.getEndLocation(), 20, 20);
        for (String item : listRange) {
            QueryWrapper<DepositoryLocationEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(ConstantFinal.FIELD_LOCATION_NAME, item);
            // 存在同名
            if (depositoryLocationService.getOne(queryWrapper) != null) {
                return R.error(CommonCodeEnum.LOCATION_EXIST.getCode(),CommonCodeEnum.LOCATION_EXIST.getMsg());
            }
        }
        List<DepositoryLocationEntity> locationEntities = new ArrayList<>();
        // 批量新增仓库
        listRange.forEach(item -> {
            DepositoryLocationEntity depositoryLocationEntity = new DepositoryLocationEntity();
            depositoryLocationEntity.setLocationName(item);
            depositoryLocationEntity.setLocationStorage(ConstantFinal.VALUE_LOCATION_NO_STORAGE);
            locationEntities.add(depositoryLocationEntity);
        });
        // 批量新增
        depositoryLocationService.saveBatch(locationEntities);
        return R.ok("批量新增仓库成功");
    }
}
